<template>
  <div>
    <!-- 上层面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="7">
          <!-- 输入框 -->
          <el-input
            placeholder="请输入内容"
            size="normal"
            v-model="queryInfo.query"
            @clear="getUserList"
            clearable
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>

        <!-- 添加用户 -->
        <el-col :span="4">
          <el-button type="primary" size="default" @click="dialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <el-table :data="userList" style="width: 100%" border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="id" label="ID" width="60"></el-table-column>
        <el-table-column
          prop="create_time"
          label="日期"
          width="180"
          algin="left"
        ></el-table-column>
        <el-table-column prop="username" label="姓名" width="180">
          <!-- 假设一种需求，继续添加个图在里面 -->
          <template slot-scope="scope">
            <div class="addImage" id="test">
              <img src="../../assets/renko.jpg" alt="头像" />
              {{ scope.row.username }}
            </div>
            <!-- 这个row是数组，可以自动[0] [1] [2] 学到了学到了 -->
            <!-- scope.row可以访问到userList的所有数据 -->
          </template>
        </el-table-column>
        <el-table-column prop="mobile" label="手机号"> </el-table-column>
        <el-table-column prop="email" label="E-mail"> </el-table-column>
        <el-table-column prop="role_name" label="用户权限"> </el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="userStateChanged(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>

        <el-table-column label="操作">
          <!-- 修改按钮位置 -->
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>

            <el-button type="danger" icon="el-icon-delete" size="mini"  @click="removeUserById(scope.row.id)" ></el-button>

            <!-- 删除用户角色分配按钮位置 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false">
              <!-- 分配角色按钮 -->
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 3, 4, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加用户界面Dialog -->
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="30%"
      @close="addDialogClosed"
    >
      <!-- title -->
      <span>添加用户</span>
      <!-- content -->

      <el-form
        :model="addUser"
        :rules="addUserRules"
        ref="addUserRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="账户" prop="username">
          <el-input v-model="addUser.username"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="addUser.password"></el-input>
        </el-form-item>

        <el-form-item label="E-mail" prop="email">
          <el-input v-model="addUser.email"></el-input>
        </el-form-item>

        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addUser.mobile"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUserValidate">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户界面Dialog -->
    <el-dialog
      title="提示"
      :visible.sync="EditDialogVisible"
      width="30%"
      :model="editForm"
    >
      <span>修改用户</span>
      <span slot="footer" class="dialog-footer">
        <!-- 修改账户名 -->
        <el-form
          :model="editForm"
          label-width="100px"
          class="demo-ruleForm"
          ref="EditUserRef"
          :rules="editUserRules">

          <el-form-item label="账户名" prop="username">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>

          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
        </el-form>

        <el-button @click="EditDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="UserEdit" @close="editDialogClosed()"
          >确 定</el-button
        >
      </span>
    </el-dialog>


    <!-- 用户管理-> 用户列表   分配角色 对话框Dialog -->
<el-dialog
  title="提示"
  :visible.sync="setRoleDialogVisible"
  width="30%">
<div>
  <p>当前用户:{{userInfo.username}}</p>
  <p>当前角色:{{userInfo.role_name}}</p>
    <el-select v-model="selectedRoleID" placeholder="请选择">
    <el-option
      v-for="item in rolesList"
      :key="item.id"
      :label="item.roleName"
      :value="item.id"  >
    </el-option>
  </el-select>
</div>

  <span slot="footer" class="dialog-footer">
    <el-button @click="setRoleDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
  </span>

</el-dialog>


  </div>
</template>

<script>
export default {
  props: ["menuListData"],
  methods: {},
  data() {
    var checkEmail = (rule, value, cb) => {
      const regEmail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
      if (regEmail.test(value)) {
        return cb();
      }

      cb(new Error("输入合法的邮箱"));
    };
    var checkMobile = (rule, value, cb) => {
      const regMobile = /^1[3-9]\d{9}$/;
      if (regMobile.test(value)) {
        return cb();
      }
      cb(new Error("输入合法的手机号"));
    };

    return {
      // 验证邮箱规则
      queryInfo: {
        query: "", //查询关键字
        pagenum: 1, // 当前页数
        pagesize: 2, //当前显示多少条数据,要显示正常需要匹配 :page-sizes="[1, 2, 5, 10]" 的值
      },

      userList: [],
      total: 0,
      dialogVisible: false, //是否隐藏添加用户页面
      EditDialogVisible: false, //是否隐藏修改用户页面
      //  添加用户表单验证
      addUserRules: {
        username: [
          { required: true, message: "请输入登录账户 ", trigger: "blur" },
          { min: 4, max: 11, message: "长度在 4 到 11个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码 ", trigger: "blur" },
          { min: 6, max: 15, message: "长度在 6 到 15个字符", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入email ", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        moblie: [
          { required: true, message: "请输入手机号 ", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      // 添加用户表单数据
      addUser: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      // 修改用户表单数据
      editForm: {},

      // 修改用户表单验证
      editUserRules: {
        email: [
          { required: true, message: "请输入正确的email ", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入正确的手机号 ", trigger: "blur" },
          { validator: checkMobile, trigger: "blur" },
        ],
      },
      // 分配角色Dialog对话框显示隐藏
      setRoleDialogVisible:false,
      userInfo:{},
      rolesList:[],
      selectedRoleID:''// 角色选框的data
    };
  },

  created() {
    this.getUserList(); // 获取用户列表users的参数对象
  },

  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo,
      });
      if (res.meta.status !== 200) {
        return this.$message.error("获取用户列表数据失败");
      }
      // 给userList传res的值
      this.userList = res.data.users;
      this.total = res.data.total;
      console.log("userList");
      console.log(res);
    },

    handleSizeChange(newSize) {
      console.log(newSize);
      this.queryInfo.pagesize = newSize;
      this.getUserList();
    },
    handleCurrentChange(newPage) {
      console.log(newPage);
      this.queryInfo.pagenum = newPage;
      this.getUserList();
    },

    // 监听Switch开关状态改变
    async userStateChanged(userinfo) {
      console.log(userinfo);
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      );
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state; //这个是页面取反限制，操作失败前端页面取反保证页面状态不要变化

        return this.$message.error("更新用户状态失败");
      }

      this.$message.success("更新用户状态成功");
    },




    // 添加用户界面关闭事件
    addDialogClosed() {
      console.log("关闭了添加用户界面");
      this.$refs.addUserRef.resetFields();
    },



    // 添加用户方法，同login一样调用端口,post请求，查看一下接口文档meta.status返回什么值
    addUserValidate() {
      this.$refs.addUserRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post("users", this.addUser);
        if (res.meta.status !== 201) {
          return this.$message.error("创建用户失败");
        }
        this.dialogVisible=false;
        return this.$message.success("创建用户成功");
      });
    },

    // 显示修改Dialog
    async showEditDialog(id) {
      const { data: res } = await this.$http.get("users/" + id);

      if (res.meta.status !== 200) {
        return this.$message.error("获取该用户信息失败");
      }
      this.editForm = res.data;
      this.EditDialogVisible = true;

      return this.$message.success("获取用户信息成功");
    },



    //  修改用户信息
    UserEdit() {
      this.$refs.EditUserRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          `users/${this.editForm.id}`,
          this.editForm
        );
        if (res.meta.status !== 200) {
          return this.$message.error("修改用户信息失败");
        }
        this.EditDialogVisible = false;
        this.getUserList();
        return this.$message.success("修改用户信息成功");
      });
    },



    // 修改用户信息Dialog关闭重置
    editDialogClosed() {
      this.$refs.EditUserRef.resetFields();
    },



    // 删除用户
    async removeUserById(id){
      console.log(id);
     const confirmResult = await this.$confirm('此操作将永久删除该用户信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)

          if(confirmResult!=='confirm'){
             return this.$message.info('已取消删除')
        }
      
          const {data:res} =await  this.$http.delete(`users/${id}`)
          if(res.meta.status!==200)
          return this.$message.error('错误')
          else{
          return this.$message.success('delete删除用户成功')
          }
         this.getUserList();
    },


    // 打开Dialog分配角色
   async setRole(userInfo){
          this.userInfo=userInfo;
          this.setRoleDialogVisible=true;
      // 为setRoleDialog获取角色数据
         const {data:res} = await this.$http.get('roles')
        if (res.meta.status !== 200) {
          return this.$message.error("获取用户失败");
        }

        this.rolesList=res.data;
  
 
        return this.$message.success("获取用户成功");
        },
        
        
    // 1.3.7.分配用户角色
    async saveRoleInfo(){
      if(!this.selectedRoleID){
        return this.$message.error('您没有分配任何角色')
      }


      const {data:res} =　await this.$http.put(`users/${this.userInfo.id}/role`,{rid: this.selectedRoleID});

      if(res.meta.status!==200){
        return this.$message.error('更新用户的角色失败')
      }

      this.$message.success('更新用户的角色成功')
    }


        
  },
      


};
</script>

<style lang="less" scoped>

</style>